package cc.springsecurity.auth2.client.token.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
public class OAuth2ServerConfig {

	private static final String DEMO_RESOURCE_ID = "product";

	@Autowired
	private RedisConnectionFactory redisConnectionFactory;

	@Bean
	public DefaultTokenServices tokenServices() {
		DefaultTokenServices tokenServices = new DefaultTokenServices();
		tokenServices.setTokenStore(new RedisTokenStore(redisConnectionFactory));
		return tokenServices;
	}

	@EnableResourceServer
	protected class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

		// 该方法可以不配置
		@Override
		public void configure(ResourceServerSecurityConfigurer resources) {
			resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
			resources.tokenServices(tokenServices());
		}

		@Override
		public void configure(HttpSecurity http) throws Exception {
			http.requestMatchers().antMatchers("/user").and().authorizeRequests().antMatchers("/user").authenticated();
		}

	}

}
